// 📊 S4策略：S3 + 连错淘汰机制（终极容错稳定版）
const _ = require("lodash");

function select32NumbersByS4(temp) {
  const allNumbers = Array.from({ length: 49 }, (_, i) =>
    (i + 1).toString().padStart(2, "0")
  );

  const windowSizes = [20, 40, 60];
  const scoreMap = {};
  const maxWrongMap = {};

  // 初始化连续错误记录
  allNumbers.forEach((n) => (maxWrongMap[n] = 0));

  // 记录最大连续错误次数（从头到尾遍历一次）
  let wrongStreakMap = {};
  allNumbers.forEach((n) => (wrongStreakMap[n] = 0));

  for (let i = 0; i < temp.length; i++) {
    const actual = temp[i].number;
    allNumbers.forEach((n) => {
      if (n === actual) {
        wrongStreakMap[n] = 0;
      } else {
        wrongStreakMap[n]++;
        maxWrongMap[n] = Math.max(maxWrongMap[n], wrongStreakMap[n]);
      }
    });
  }

  // 构造冷却列表：连续错误 ≥ 4 的号码
  const cooldownNumbers = allNumbers.filter((n) => maxWrongMap[n] >= 4);

  // 多窗口融合评分
  windowSizes.forEach((winSize) => {
    const subTemp = temp.slice(-winSize);
    const freqMap = {};
    const lastAppearMap = {};
    const wrongStreakMapLocal = {};

    allNumbers.forEach((n) => (wrongStreakMapLocal[n] = 0));

    for (let i = subTemp.length - 1; i >= 0; i--) {
      const num = subTemp[i].number;

      allNumbers.forEach((n) => {
        if (n === num) {
          wrongStreakMapLocal[n] = 0;
        } else {
          wrongStreakMapLocal[n]++;
        }
      });

      freqMap[num] = (freqMap[num] || 0) + 1;
      lastAppearMap[num] = i;
    }

    // 评分逻辑
    allNumbers.forEach((n) => {
      // ❄️ 如果是冷却号码，则给予严重扣分
      const cooldownPenalty = cooldownNumbers.includes(n) ? -20 : 0;


      const freq = freqMap[n] || 0;
      const lastIndex = lastAppearMap[n];
      const gap =
        lastIndex !== undefined
          ? subTemp.length - 1 - lastIndex
          : subTemp.length;
      const wrong = wrongStreakMapLocal[n] || 0;


      const score = freq * 2 + gap * 1 - wrong * 1.5 + cooldownPenalty;

      scoreMap[n] = (scoreMap[n] || 0) + score;
    });
  });

  // 得分排序后选出 32 个
  const result = Object.entries(scoreMap)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 32)
    .map(([num]) => num);

  return result;
}

module.exports = select32NumbersByS4;
